<template>
  <div>
    <div class="analysisGeneration-content1">
      <el-form :model="propsData" ref="analysisGeneration-content1" class="analysisGeneration-content1-form">
        <el-form-item label="标题名称" prop="name" class="s" :rules="[{ required: true, message: '请输入标题名称', trigger: 'blur' }]">
          <el-input placeholder="标题名称" v-model="propsData.name" clearable/>
        </el-form-item>
        <el-form-item label="资产配置名称" prop="type" class="s" :rules="[{ required: true, message: '请输入资产配置名称', trigger: 'blur' }]">
          <el-input placeholder="资产配置名称" v-model="propsData.type" clearable/>
        </el-form-item>
        <el-form-item label="资产配置id" prop="assetProfileId" class="s" :rules="[{ required: true, message: '请输入资产配置id', trigger: 'blur' }]">
          <el-input placeholder="资产配置id" v-model="propsData.assetProfileId" clearable/>
        </el-form-item>
        <el-form-item label="路由name" prop="permissionRouting" class="s" :rules="[{ required: true, message: '请输入路由nameid', trigger: 'blur' }]">
          <el-input placeholder="路由name-text1:text2" v-model="propsData.permissionRouting" clearable/>
        </el-form-item>


      </el-form>
      <div style="margin-left: 25px">
        <el-upload
            class="upload-demo" ref="upload"
            accept=".xls,.xlsx"
            action="https://jsonplaceholder.typicode.com/posts/"
            :on-change="upload"
            :show-file-list="false"
            :auto-upload="false"
        >
          <el-button slot="trigger" icon="el-icon-download el-icon--left" type="primary">导入解析生产字段
          </el-button>
        </el-upload>
      </div>
    </div>
    <div class="analysisGeneration-content3">
      <el-button type="success" size="medium" @click="generatePageCodeClick">生成页面代码</el-button>
      <el-button type="info" size="medium" @click="temporaryStorage1">暂存当前生成数据</el-button>
      <el-button type="warning" size="medium" @click="temporaryStorage2">读取前面暂存的数据</el-button>
      <el-upload
          class="upload-demo" ref="upload"
          accept=".js"
          action="https://jsonplaceholder.typicode.com/posts/"
          :on-change="importBackupClick"
          :show-file-list="false"
          :auto-upload="false"
      >
        <el-button slot="trigger" type="primary" style="margin: 0 12px">导入备份生成器数据
        </el-button>
      </el-upload>
      <el-button type="danger" size="medium" @click="initializationClcik">初始化</el-button>
    </div>

    <!--表格配置-->
    <tableSet :propsData="propsData"></tableSet>


  </div>
</template>

<script>
import XLSX from 'xlsx'
import {saveAs} from 'file-saver';
import tableSet from "@/views/thingsBoard/tableSet.vue";
import {v4 as uuidv4} from 'uuid';

export default {
  components: {tableSet},
  props: [],
  data() {
    return {
      //导出文件集合
      exportFileData: [],
      endScript: '</scr' + 'ipt>',
      allStyle: '<style lang="scss" scoped></style>',
      propsData: {
        name: '',//标题名称
        type: '',//资产配置名称
        assetProfileId: '',//资产配置id
        permissionRouting: '',//路由name 必须 text1:text2  用来做权限按钮
        //表格配置
        tableProp: {
          tableArray: []
        }
      }
    };
  },
  mounted() {
    console.log(uuidv4());
  },
  methods: {
    //生产代码
    generatePageCodeClick() {
      this.exportFileData = [];
      this.$refs['analysisGeneration-content1'].validate(valid => {
        if (!valid) {
          return false
        }
        if (this.propsData.tableProp.tableArray.length == 0) {
          this.$message.info('请先添加字段');
          return false;
        }
        let searchFieldBoolean = false;
        for (let i = 0; i < this.propsData.tableProp.tableArray.length; i++) {
          if (this.propsData.tableProp.tableArray[i].searchField) {
            searchFieldBoolean = this.propsData.tableProp.tableArray[i].searchField;
            continue
          }
        }
        if (!searchFieldBoolean) {
          this.$message.info('搜索字段就是资产名称,必须选一个');
          return false;
        }
        let tableArrayAll = this.propsData.tableProp.tableArray.sort(function (p1, p2) { //如果返回负数 p1在前 如果返回正数 p2在前
          return p1.sort - p2.sort
        })

        //搜索字段就是资产名称 开始
        let searchFieldName = '';
        for (let i = 0; i < tableArrayAll.length; i++) {
          if (tableArrayAll[i].searchField) {
            searchFieldName = tableArrayAll[i].name;
          }
        }
        //搜索字段就是资产名称 结束

        // 表格vue开始
        let tableVue = ``;
        for (let i = 0; i < tableArrayAll.length; i++) {
          if (tableArrayAll[i].searchField) {
            tableVue += `<el-table-column label="${tableArrayAll[i].name}" min-width="150" align="center" prop="name" :show-overflow-tooltip="true" v-if="tableColumnShow('${tableArrayAll[i].name}')"/>
`
            continue
          }
          if (['输入框', '文本框', '日期选择器'].includes(tableArrayAll[i].type)) {
            tableVue += `<el-table-column label="${tableArrayAll[i].name}" min-width="150" align="center" :show-overflow-tooltip="true" v-if="tableColumnShow('${tableArrayAll[i].name}')">
            <template #default="scope">
              {{ tableFieldShow('${tableArrayAll[i].name}', scope.row.field) }} ${tableArrayAll[i].unit}
            </template>
          </el-table-column>
`
            continue
          }
          if (['下拉框', '单选框'].includes(tableArrayAll[i].type)) {
            tableVue += `<el-table-column label="${tableArrayAll[i].name}" min-width="150" align="center" :show-overflow-tooltip="true" v-if="tableColumnShow('${tableArrayAll[i].name}')">
            <template #default="scope">
              {{ handleTypeOptions(tableFieldShow('${tableArrayAll[i].name}', scope.row.field), optionsLisi.${tableArrayAll[i].name}Options) }}
            </template>
          </el-table-column>
`
            continue
          }
        }
        //表格vue结束

        //抽屉查看vue开始
        let seeDrawerVue = ``;
        for (let i = 0; i < tableArrayAll.length; i++) {
          if (tableArrayAll[i].searchField) {
            seeDrawerVue += `<li class="width50"><span>${tableArrayAll[i].name}：</span>{{ queryData.name }}</li>
`
            continue
          }
          if (['输入框', '文本框', '日期选择器'].includes(tableArrayAll[i].type)) {
            seeDrawerVue += ` <li class="width50"><span>${tableArrayAll[i].name}：</span>{{ tableFieldShow('${tableArrayAll[i].name}', queryData.field) }}</li>
`
            continue
          }
          if (['下拉框', '单选框'].includes(tableArrayAll[i].type)) {
            seeDrawerVue += ` <li class="width50"><span>${tableArrayAll[i].name}：</span>{{ handleTypeOptions(tableFieldShow('${tableArrayAll[i].name}', queryData.field), optionsLisi.${tableArrayAll[i].name}Options) }}</li>
`
            continue
          }
        }
        //抽屉查看vue结束

        //抽屉编辑vue开始
        let editDrawerVue = ``;
        for (let i = 0; i < tableArrayAll.length; i++) {
          if (tableArrayAll[i].searchField) {
            editDrawerVue += ` <el-form-item label="${tableArrayAll[i].name}：" prop="name" class="edit-content-form-li width50" :rules="[{ required: true, message: '请输入${tableArrayAll[i].name}', trigger: 'blur' }]">
                <el-input placeholder="请输入${tableArrayAll[i].name}" v-model="formData.name" clearable/>
              </el-form-item>
`
            continue
          }
          if (['输入框'].includes(tableArrayAll[i].type)) {
            let rules = `[]`;
            if (tableArrayAll[i].isRequired) {
              rules = `[{ required: true, message: '请输入${tableArrayAll[i].name}', trigger: 'blur' }]`;
            }
            let append = ``;
            if (tableArrayAll[i].unit) {
              append = `<template #append>${tableArrayAll[i].unit}</template>`
              editDrawerVue += `<el-form-item label="${tableArrayAll[i].name}：" prop="field.${tableArrayAll[i].name}" class="edit-content-form-li width50" :rules="${rules}">
                <el-input placeholder="请输入${tableArrayAll[i].name}" v-model="formData.field.${tableArrayAll[i].name}" clearable>
                  ${append}
                </el-input>
              </el-form-item>
`
            }else{
              editDrawerVue += `<el-form-item label="${tableArrayAll[i].name}：" prop="field.${tableArrayAll[i].name}" class="edit-content-form-li width50" :rules="${rules}">
                <el-input placeholder="请输入${tableArrayAll[i].name}" v-model="formData.field.${tableArrayAll[i].name}" clearable/>
              </el-form-item>
`
            }
            continue
          }
          if (['文本框'].includes(tableArrayAll[i].type)) {
            let rules = `[]`;
            if (tableArrayAll[i].isRequired) {
              rules = `[{ required: true, message: '请输入${tableArrayAll[i].name}', trigger: 'blur' }]`;
            }
            editDrawerVue += `<el-form-item label="${tableArrayAll[i].name}：" prop="field.${tableArrayAll[i].name}" class="edit-content-form-li width50" :rules="${rules}">
                  <el-input placeholder="请输入${tableArrayAll[i].name}" v-model="formData.field.${tableArrayAll[i].name}" :autosize="{ minRows: 4, maxRows: 10 }" type="textarea" clearable/>
              </el-form-item>
`
            continue
          }
          if (['下拉框'].includes(tableArrayAll[i].type)) {
            let rules = `[]`;
            if (tableArrayAll[i].isRequired) {
              rules = `[{ required: true, message: '请选择${tableArrayAll[i].name}', trigger: 'blur' }]`;
            }
            editDrawerVue += `<el-form-item label="${tableArrayAll[i].name}：" prop="field.${tableArrayAll[i].name}" class="edit-content-form-li width50" :rules="${rules}">
                   <el-select placeholder="请选择${tableArrayAll[i].name}" v-model="formData.field.${tableArrayAll[i].name}" filterable clearable>
                  <el-option v-for="item in optionsLisi.${tableArrayAll[i].name}Options" :key="item.value" :label="item.label" :value="item.value"/>
                </el-select>
              </el-form-item>
`
            continue
          }
          if (['单选框'].includes(tableArrayAll[i].type)) {
            let rules = `[]`;
            if (tableArrayAll[i].isRequired) {
              rules = `[{ required: true, message: '请选择${tableArrayAll[i].name}', trigger: 'blur' }]`;
            }
            editDrawerVue += `<el-form-item label="${tableArrayAll[i].name}：" prop="field.${tableArrayAll[i].name}" class="edit-content-form-li width50" :rules="${rules}">
                    <el-radio-group v-model="formData.field.${tableArrayAll[i].name}">
                  <el-radio v-for="item in optionsLisi.${tableArrayAll[i].name}Options" :key="item.value" :value="item.value">{{item.label}}</el-radio>
                </el-radio-group>
              </el-form-item>
`
            continue
          }
          if (['日期选择器'].includes(tableArrayAll[i].type)) {
            let rules = `[]`;
            if (tableArrayAll[i].isRequired) {
              rules = `[{ required: true, message: '请选择${tableArrayAll[i].name}', trigger: 'blur' }]`;
            }
            editDrawerVue += `<el-form-item label="${tableArrayAll[i].name}：" prop="field.${tableArrayAll[i].name}" class="edit-content-form-li width50" :rules="${rules}">
                    <el-date-picker class="width100" v-model="formData.field.${tableArrayAll[i].name}" type="date" placeholder="请选择${tableArrayAll[i].name}" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
              </el-form-item>
`
            continue
          }
        }
        //抽屉编辑vue结束

        //表单字段 开始
        let fromData = ``;
        for (let i = 0; i < tableArrayAll.length; i++) {
          if (!tableArrayAll[i].searchField) {
            fromData += `${tableArrayAll[i].name}: '',//${tableArrayAll[i].name}
            `
          }
        }
        //表单字段 结束

        // 下拉选项 开始
        let optionData = '';//下拉选项数据
        for (let i = 0; i < tableArrayAll.length; i++) {
          //下拉选项数据
          if (['下拉框', '单选框'].includes(tableArrayAll[i].type)) {
            let str = `[
                                ${tableArrayAll[i].selectProp.text}
                           ]`;
            optionData += `//${tableArrayAll[i].name} 选项
                                   ${tableArrayAll[i].name}Options:${str},
                        `
          }
        }
        //下拉选项 结束

        //编辑方法里的字段 开始
        let editFormData = ``;
        for (let i = 0; i < tableArrayAll.length; i++) {
          if (!tableArrayAll[i].searchField) {
            editFormData += `formData.value.field.${tableArrayAll[i].name} = tableFieldShow('${tableArrayAll[i].name}', row.field);//${tableArrayAll[i].name}
            `
          }
        }
        //编辑方法里的字段 结束

        //删除方法使用开始
        let delData = "`确定要删除 '${row.name}' 吗？`"
        //删除方法使用结束

        //表格tableColumns 显示隐藏数据 开始
        let tableColumnsData = ``;
        for (let i = 0; i < tableArrayAll.length; i++) {
          tableColumnsData += `{label: '${tableArrayAll[i].name}', visible: true},
            `
        }
        //表格tableColumns 显示隐藏数据 结束


        let allVue = `<template>
  <div class="cc-main">
    <div class="cc-main-content">
      <!--title-->
      <div class="cc-title-css">
        <div class="left">
          <el-icon class="left-icon">
            <Tickets/>
          </el-icon>
          <!--标题名称-->
          <span>{{ titleConfig.name }}</span></div>
        <!--右边的按钮-->
        <div class="right">
          <el-button type="primary" plain :icon="Plus" @click="addClick(titleConfig.addButName)" v-hasPermi="['${this.propsData.permissionRouting}:create']"> {{ titleConfig.addButName }}</el-button>
        </div>
      </div>
<!--搜索内容字段-->
      <div class="cc-search-css" ref="searchRef">
        <el-form class="-mb-15px" :model="searchForm" ref="searchFormRef" :inline="true" label-width="68px">
          <!--@keyup.enter="handleQuery"-->
          <el-form-item label="${searchFieldName}" prop="name">
            <el-input v-model="searchForm.name" placeholder="请输入${searchFieldName}" clearable class="!w-240px"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchClick">
              <Icon icon="ep:search" class="mr-5px"/>
              搜索
            </el-button>
            <el-button @click="searchResetClick">
              <Icon icon="ep:refresh" class="mr-5px"/>
              重置
            </el-button>
            <!--表格字段是否显示-->
            <el-dropdown trigger="click" :hide-on-click="false" style="padding-left: 12px">
              <el-button circle :icon="Menu"/>
              <template #dropdown>
                <el-dropdown-menu>
                  <template v-for="item in tableColumns" :key="item.visible">
                    <el-dropdown-item>
                      <el-checkbox v-model="item.visible" :label="item.label"/>
                    </el-dropdown-item>
                  </template>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-form-item>
        </el-form>
      </div>
      <!--table-->
      <div class="cc-table-css">
        <el-table
            ref="tableRef"
            :data="tableData"
            border
            style="width: 100%"
            :header-cell-style="getHeaderCellStyle"
            v-loading="tableConfig.loading"
            :max-height="tableConfig.height"
        >
          <el-table-column label="序号" type="index" width="55" align="center" fixed="left"/>
          ${tableVue}
          <el-table-column width="300" fixed="right" label="操作" align="center">
            <template #default="scope">
              <el-button type="success" :icon="View" :plain="true" @click="queryClick(scope.row)" v-hasPermi="['${this.propsData.permissionRouting}:query']">详细</el-button>
              <el-button type="primary" :icon="EditPen" :plain="true" @click="editClick(scope.row)" v-hasPermi="['${this.propsData.permissionRouting}:update']">编辑</el-button>
              <el-button type="danger" :icon="Delete" :plain="true" @click="delClick(scope.row)" v-hasPermi="['${this.propsData.permissionRouting}:delete']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="cc-table-css-page">
          {{ tableConfig.currentPage }}
          <el-pagination
              @size-change="pageSizeChange"
              @current-change="pageCurrentChange"
              :page-size="tableConfig.pageSize"
              :page-sizes="[10, 20, 50, 100,500,1000]"
              layout="total,sizes, prev, pager, next, jumper"
              :current-page="tableConfig.currentPage"
              :total="tableConfig.total"
          />
        </div>
      </div>
       <!--抽屉-->
      <el-drawer
          :title="drawerConfig.title"
          v-model="drawerConfig.isDrawer"
          direction="rtl"
          :append-to-body="true"
          class="cc-drawer-css"
          size="1200px"
      >
        <!--头部配置-->
        <template header>
          <span>{{ drawerConfig.title }}</span>
        </template>

        <div class="drawer-content">

          <!--tabs选项-->
          <el-tabs v-model="drawerConfig.active" class="content-top-tabs" @tab-click="tabsClick">
            <el-tab-pane label="基础信息" name="1" v-if="drawerConfig.type=='add'"/>
            <el-tab-pane v-else v-for="item in drawerConfig.tabsList" :key="item.value" :label="item.label" :name="item.value"/>
          </el-tabs>

          <!--查看 li添加class width100 width50 width33 就可以一列 二列 三列-->
          <div class="see-content" v-loading="drawerConfig.loading" v-if="drawerConfig.type==='query'">
            <ul>
                ${seeDrawerVue}
            </ul>
          </div>

          <!--编辑 edit-content-form-li 里面添加 width100 width50 width33 就可以一列 二列 三列-->
          <div class="edit-content" v-loading="drawerConfig.loading" v-else>
            <el-form :model="formData" ref="drawerFromRef" class="edit-content-form" label-width="140px">
              ${editDrawerVue}
            </el-form>
          </div>
        </div>

        <!--新增的时候-->
        <div class="action-button" v-if="['add', 'edit'].includes(drawerConfig.type) && !drawerConfig.loading">
          <el-button :icon="Close" @click="drawerConfig.isDrawer=false">取 消</el-button>
          <el-button type="primary" :icon="Check" @click="drawerSubmitForm(drawerFromRef)">保 存</el-button>
        </div>
      </el-drawer>

    </div>
  </div>
</template>
`
        let vueData = `
            ${allVue}
            <script lang="ts" setup>
            import {ref, reactive, onMounted} from 'vue'
            import {Tickets, Plus, EditPen, Delete, View, Menu, Close, Check} from '@element-plus/icons-vue'
            import {handleTypeOptions, tableFieldShow} from '@/utils/thingsBoardUtils'
            import {assetsDel, assetsEdit, assetsEditField, assetsList, assetsListField} from "@/api/genchuan/thingsBoard/assets";
            //table 初始化
            const tableInitData = async () => {
              tableConfig.value.loading = true;
              try {
                let params = {
                  pageSize: tableConfig.value.pageSize,
                  page: tableConfig.value.currentPage - 1,
                  textSearch: searchForm.value.name,
                  sortProperty: 'createdTime',
                  sortOrder: 'DESC',
                  assetProfileId: '${this.propsData.assetProfileId}',//资产配置id
                }
                let res = await assetsList(params);
                tableData.value = res.data;
                for (let i = 0; i < tableData.value.length; i++) {
                  let params = {id: tableData.value[i].id.id}
                  let resField = await assetsListField(params);
                  tableData.value[i].field = resField
                }
                tableConfig.value.total = res.totalElements;
                tableConfig.value.loading = false;
              } catch (error) {
                tableConfig.value.loading = false;
                // 处理错误
                console.log("初始化出错了")
              }
            }

            // 表单字段
              const initFormData = {
                name: '',//资产名称 这个用一个字段区代表就行了
                type: '${this.propsData.type}',//资产配置，都是写死固定的资产配置
                field: {
                   ${fromData}
                }
              }

              // 所有选项集合
            const optionsLisi = ref({
              ${optionData}
            })

            // 表单初始化数据
            const formData = ref({...initFormData});

            //表单保存
            const drawerFromRef = ref<FormInstance>()
            const drawerSubmitForm = async (formEl: FormInstance | undefined) => {
              if (!formEl) return
              const valid = await new Promise<boolean>((resolve) => {
                formEl.validate((valid) => {
                  resolve(valid);
                });
              });
              if (valid) {
                try {
                  let res = await assetsEdit(formData.value);
                  await assetsEditField(res.id.id, formData.value.field)
                  if (drawerConfig.value.type === 'add') {
                    tableConfig.value.currentPage = 1;
                  }
                  drawerConfig.value.isDrawer = false;
                  ElMessage.success('保存成功');
                  await tableInitData();
                } catch (error) {
                  if (drawerConfig.value.type === 'add') {
                    ElMessage.error('保存失败，数据重复');
                  }
                  console.log('新增出错!', error);
                }
              } else {
                console.log('表单验证出错!');
                // ElMessage.warning('请完善表单信息');
              }
            }

            // 点击详细按钮
            const queryData = ref({})
            const queryClick = async (row) => {
              queryData.value = row;
              console.log(row)
              drawerConfig.value.isDrawer = true;
              drawerConfig.value.loading = false;
              drawerConfig.value.type = 'query';
              drawerConfig.value.title = '${this.propsData.name}-详细信息';
            }
            // 点击编辑按钮
            const editClick = async (row) => {
              let copyRow = JSON.parse(JSON.stringify(row))
              formData.value = copyRow;
              formData.value.field = {};
              ${editFormData}
              drawerConfig.value.isDrawer = true;
              drawerConfig.value.loading = false;
              drawerConfig.value.type = 'edit';
              drawerConfig.value.title = '编辑${this.propsData.name}';
            }
            // 点击删除按钮
            const delClick = (row) => {
              ElMessageBox.confirm(
                  '请注意：确认后，所有相关数据将不可恢复。',
                   ${delData},
                  {
                    confirmButtonText: '确 定',
                    cancelButtonText: '取 消',
                    type: 'warning',
                  }
              )
                  .then(async () => {
                    try {
                      await assetsDel(row.id.id)
                      await tableInitData();
                      ElMessage({
                        type: 'success',
                        message: '删除成功',
                      })
                    } catch (error) {
                      // 处理错误
                      console.log(error)
                    }
                  })
                  .catch(() => {
                    console.log('取消删除')
                  })
            }
            // title点击新增
            const addClick = async () => {
              formData.value = {
                ...initFormData,
                field: {...initFormData.field}
              };
              drawerConfig.value.isDrawer = true;
              drawerConfig.value.loading = false;
              drawerConfig.value.type = 'add';
              drawerConfig.value.title = '新增${this.propsData.name}';
            }

            //drawer 配置
            const drawerConfig = ref({
              isDrawer: false,//是否打开抽屉 true 打开 false 关闭
              loading: true,//还没加载完成 true 在加载 false加载完成
              title: '抽屉标题',//标题名称
              type: 'add',//add新增 edit编辑 query详细
              active: '1',//当前选择了哪个
              // tabs轮动
              tabsList: [
                {label: '基础信息', name: '1'},
              ]
            })
            //drawer tabs 点击切换
            const tabsClick = (tab) => {
              tableConfig.value.currentPage = 1;//当前第几页
              tableInitData();
              console.log('tabs点击切换', tab.props.name)
            }
            // title配置
            const titleConfig = ref({
              name: '${this.propsData.name}',//标题名称
              addButName: '新增${this.propsData.name}',//新增按钮名称
            })
            // 搜索 字段
            const initSearchForm = {
              name: '',//配置名称
            }
            // 搜索初始化数据
            const searchForm = ref({...initSearchForm});
            // 搜索 点击
            const searchClick = () => {
              tableConfig.value.currentPage = 1;
              tableInitData();
            }
            //搜索 重置
            const searchResetClick = () => {
              searchForm.value = {...initSearchForm};
              tableConfig.value.currentPage = 1;
              tableInitData();
            }
            //table 列显隐信息
          const tableColumns = ref([
            ${tableColumnsData}
          ])
          // table表格数据
          const tableData = ref([])
          //table 配置
          const tableConfig = ref({
            height: 0,//表格高度
            loading: true,//是否加载完成
            currentPage: 1,//当前第几页
            pageSize: 10,//每页几条
            total: 0,//总数
          })
          //table 列是否显示
          const tableColumnShow = (label) => {
            for (let i = 0; i < tableColumns.value.length; i++) {
              if (tableColumns.value[i].label === label) {
                return tableColumns.value[i].visible
              }
            }
          }
          //table 设置高度
          const searchRef = ref(null);
          const getTableHeight = () => {
            setTimeout(() => {
              if (searchRef.value) {
                const searchHeight = searchRef.value.clientHeight;
                let height = document.documentElement.clientHeight - searchHeight - 52 - 107 - 70
                tableConfig.value.height = height
              }
            }, 300)
          }
          //table 给表头加样式
          const getHeaderCellStyle = () => {
            return {
              background: '#f5f7fa',
              color: '#081333',
              fontWeight: 'normal'
            };
          };
          //table 分页 选择了每页几条
          const pageSizeChange = (val) => {
            tableConfig.value.currentPage = 1;//当前第几页
            tableConfig.value.pageSize = val;//每页几条
            tableInitData();
          };
          //table 分页 点击了跳转到第几页
          const pageCurrentChange = (val) => {
            tableConfig.value.currentPage = val;//当前第几页
            tableInitData();
          };

          // 定义要添加到 body 的 class 名称
          const customClass = 'thingsBoard-body-class';
          const addClassToBody = () => {
            document.body.classList.add(customClass);
          };
          const removeClassFromBody = () => {
            document.body.classList.remove(customClass);
          };

          // 挂载完毕
          onMounted(() => {
            console.log('挂载完毕2')
            addClassToBody();//给body加class控制样式
            getTableHeight();//给table获取高度
            tableInitData();//数据初始化
          })
          // 在组件卸载时移除 class
          onUnmounted(() => {
            removeClassFromBody();
          });
          ${this.endScript}
            ${this.allStyle}
        `


        let vueName=this.propsData.permissionRouting.split(':')

        //生成 vue
        let jsonData = {
          name: `${vueName[1]}.vue`,//文件名称
          data: vueData,
          status: `vue文件`,
        }
        this.exportFileData.push(jsonData);

        //生成备份生成器生成数据文件 开始
        let backupsData = {
          name: `${vueName[1]}Backups.js`,//文件名称
          data: JSON.stringify(this.propsData),
          status: `${vueName[1]}备份生成器生成数据文件`,
        }
        this.exportFileData.push(backupsData);

        //生成文件
        if (this.exportFileData.length) {
          (async () => {
            //-----------------------------------------------------
            //批量生成路由文件
            for (let i = 0; i < this.exportFileData.length; i++) {
              await this.Utils.delay(1000);
              //生成文件
              let codeStr = this.exportFileData[i].data;
              let blob = new Blob([codeStr], {type: 'text/plain;charset=utf-8'})
              saveAs(blob, this.exportFileData[i].name)
            }
          })();
        }


        // console.log(vueData)

      })
    },

    //导入表格
    upload(file) {// fileList
      let files = {0: file.raw}// 取到File
      this.readExcel(files)
    },
    readExcel(files) { // 表格导入
      if (files.length <= 0) { // 如果没有文件名
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message.success('上传格式不正确，请上传xls或者xlsx格式');
        return false
      }
      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0]// 取第一张表
          const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容
          //数据处理
          this.propsData.tableProp.tableArray = [];
          for (let i = 0; i < ws.length; i++) {
            let optionsList = `{label:'',value:''},`
            let type = '输入框';//数据类型
            if (ws[i].值域) {
              let optionsRes1 = ws[i].值域.split("；");
              let optionsRes2 = "";
              for (let j = 0; j < optionsRes1.length; j++) {
                let aa = optionsRes1[j].split("-");
                optionsRes2 += `{label:'${aa[1]}',value:'${aa[0]}'},`
              }
              optionsList = optionsRes2;
              type = '下拉框';
            }
            let jsonData = {
              id: uuidv4(),
              name: ws[i].中文名称,//名称
              type: type,//数据类型
              sort: (i + 1) * 50,//排序
              unit: ws[i].计量单位 ? ws[i].计量单位 : '',//单位
              searchField: false,//搜索字段就是资产名称
              isRequired: false,//是否必填 true是
              //单选框-下拉框-多选框 数据来源
              selectProp: {
                text: optionsList,
              }
            }
            this.propsData.tableProp.tableArray.push(jsonData);
            console.log(this.propsData.tableProp.tableArray)
          }
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    },
    //初始化
    initializationClcik() {
      this.$confirm('此操作将刷新页面初始化?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$router.go(0);
      }).catch(() => {
        this.$message.info('已取消初始化');
      });
    },
    //暂存当前生成数据
    temporaryStorage1() {
      this.$confirm('是否暂存当前生成数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        window.localStorage.setItem('propsData', JSON.stringify(this.propsData));
        this.$message.success('暂存成功');
      }).catch(() => {
        this.$message.info('已取消暂存当前生成数据');
      });
    },
    //读取前面暂存的数据
    temporaryStorage2() {
      this.$confirm('是否读取前面暂存的数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let propsData = window.localStorage.getItem('propsData');
        if (propsData) {
          let propsDataCody = JSON.parse(propsData)
          this.propsData = propsDataCody;
          this.$message.success('读取成功');
        } else {
          this.$message.error('暂无暂存数据');
        }
      }).catch(() => {
        this.$message.info('已取消读取前面暂存的数据');
      });
    },
    //导入备份生成器数据
    importBackupClick(file) {
      console.log(23123)
      const reader = new FileReader()
      reader.readAsText(file.raw)
      reader.onload = (event) => {
        let propsData = event.target.result;
        let propsDataCody = JSON.parse(propsData)
        this.propsData = propsDataCody;
        this.$message.success('导入成功');
      }
    },
  }
};
</script>

<style lang="scss" scoped></style>
